<template>
  <div class="w-full">
    <el-tabs v-model="activeTab" class="w-full">
      <el-tab-pane label="上传" name="upload">
        <UploadFile v-model="src" title="选择" multiple @fileListChange="fileListChange" />
      </el-tab-pane>
      <el-tab-pane label="文件库选择" name="second">
        <ElButton @click="resourceVisible = true">打开文件库</ElButton>
        <ResourcePicker v-model:visible="resourceVisible" multiple @confirm="confirmResource" />
      </el-tab-pane>
    </el-tabs>
    <ElCard class="w-full mt-4">
      <template #header>
        已选/已上传：
      </template>
      <div v-if="resources?.length > 0">
        <div v-for="(res, idx) in resources" class="flex items-center justify-between">
          <span>{{ res.origin_name }}</span>
          <span class="ml-4 cursor-pointer" @click="removeResource(idx)">
            <el-icon class="">
              <Delete />
            </el-icon>
          </span>
        </div>
      </div>

      <div v-else>
        未选择
      </div>

    </ElCard>

  </div>
</template>

<script setup lang='ts'>
import UploadFile from '@/components/ma-upload-file/index.vue'
import ResourcePicker from '@/components/ma-resource-picker/index.vue'
import { Delete } from '@element-plus/icons-vue'
const activeTab = ref('upload');
const resourceVisible = ref<boolean>(false);
const model = defineModel({
  default: []
}) as any;
const src = ref([]);
const resources = ref(model.value || []);

const formatFiles = files => files.map(file => ({
  url: file.url,
  origin_name: file.origin_name,
  suffix: file.suffix,
  mime_type: file.mime_type,
}))
const confirmResource = files => {
  resources.value.push(...formatFiles(files));
}
const fileListChange = (fileList) => {
  const files = fileList.map(file => toRaw(file.response.data));
  resources.value.push(...formatFiles(files));
}
const removeResource = (idx: number) => {
  resources.value.splice(idx, 1)
}
watch(()=>resources.value,(v)=>{
  console.log(resources.value)
  model.value = v
},{
  deep:true
})
</script>

<style></style>
